package zero.tech.core;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

import zero.tech.core.event.EventListenerManager;
import zero.tech.core.work.WorkManager;
@Configuration
public class ZeroContext implements ApplicationContextAware {
	public static ApplicationContext applicationContext;
	private static volatile boolean flag=false;
	@SuppressWarnings("unchecked")
	public static <T> T getInstance(Class<?> clz) {
		Object obj = applicationContext.getBean(clz);
		if (obj == null) {
			String clzName = clz.getSimpleName();
			String first = String.valueOf(clzName.charAt(0));
			clzName = first.toLowerCase() + clzName.substring(1);
			obj = applicationContext.getBean(clzName);
		}
		return (T) obj;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getInstance(String name) {
		return (T)applicationContext.getBean(name);
	}
	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		if(!flag) {
			applicationContext = context;
			configInit();
			flag=true;
		}
	}

	private void configInit() {
		try {
			WorkManager.getManager().start();
			EventListenerManager.getManager().start();
			
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	
	public static void registerSingleton(String beanName,Object singletonObject) {
		ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
		DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
		defaultListableBeanFactory.registerSingleton(beanName, singletonObject);
	}
}
